package com.xindaoapp.happypet.protocol;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONObject;

import android.text.TextUtils;
import android.util.Pair;

import com.xindaoapp.happypet.XDHttpClient;
import com.xindaoapp.happypet.api.ConstantsValue;
import com.xindaoapp.happypet.protocol.CustomMultipartEntity.ProgressListener;
import com.xindaoapp.happypet.utils.LogUtil;

/**
 * 发帖
 * 
 * @author chenghao
 * 
 */
public class UploadPostImpl implements UploadPost {

    @Override
    public Pair<Boolean, String> post(String uid, String fid, File imageFile,
            ProgressListener iProgressListener) {
        CustomMultipartEntity mpEntity = new CustomMultipartEntity(iProgressListener); // 文件传输
        try {
            if (null != imageFile) {// 上传图片
                mpEntity.addPart(MoccaApi.PARAM_TYPE, new StringBody(MoccaApi.IMG));
                mpEntity.addPart("Filedata", new FileBody(imageFile, "image/jpeg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String strReturn = "";
        try {
            JSONObject result = new JSONObject(post(MoccaApi.NEWATTACHMENTURL, mpEntity));
            if (result.getInt("result") == 0 && result.has("aid")) {
                return new Pair<Boolean, String>(true, result.getString("aid"));
            } else {
                strReturn = result.getString("msg").toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            strReturn = "发送失败，已保存到草稿箱";
        }
        return new Pair<Boolean, String>(false, strReturn);
    }

    @Override
    public Pair<Boolean, String> post(String uid, String fid, File videoFile, File coverFile,
            ProgressListener iProgressListener) {
        CustomMultipartEntity mpEntity = new CustomMultipartEntity(iProgressListener); // 文件传输
        try {
            if (null != videoFile) {// 上传视频文件
                mpEntity.addPart(MoccaApi.PARAM_TYPE, new StringBody(MoccaApi.VIDEO));
                mpEntity.addPart(MoccaApi.COVERIMG, new FileBody(coverFile, "image/jpeg"));
                mpEntity.addPart("Filevideo", new FileBody(videoFile, "video/mp4"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String strReturn = "";
        try {
            JSONObject result = new JSONObject(post(MoccaApi.VIDREQUESTURL, mpEntity));
            if (result.getInt("result") == 0 && result.has("videoid")) {
                return new Pair<Boolean, String>(true, result.getString("videoid"));
            } else {
                strReturn = result.getString("msg").toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            strReturn = "发送失败，已保存至草稿箱";
        }
        return new Pair<Boolean, String>(false, strReturn);
    }

    /**
     * 网络请求
     * 
     * @param url
     * @param mpEntity
     * @return
     */
    private String post(String url, CustomMultipartEntity mpEntity) {
        DefaultHttpClient httpclient = (DefaultHttpClient) XDHttpClient.client.getHttpClient();
        if (ConstantsValue.cookieStore != null) {
            httpclient.setCookieStore(ConstantsValue.cookieStore);
        }
        // 设置通信协议版本
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
                HttpVersion.HTTP_1_1);
        HttpPost httppost = new HttpPost(url);
        httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
        // 读取超时
        httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
        httppost.setEntity(mpEntity);
        String result = "";
        try {
            HttpResponse execute = httpclient.execute(httppost);
            int resStatu = execute.getStatusLine().getStatusCode();// 返回码
            LogUtil.info("发送帖子返回码：" + resStatu);
            final byte[] responseBody = getResponseData(execute.getEntity());
            result = new String(responseBody, "gbk").toString();
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result = "发送失败，已保存到草稿箱";
        } finally {
            if (httppost != null) {
                httppost.abort();
            }
        }
        return result;
    }

    @Override
    public Pair<Boolean, String> post(String uid, String fid, String title, String content,
            String aidList, String videoAidList, String webvideodata, int isSendShared,
            ProgressListener iProgressListener) {
        CustomMultipartEntity mpEntity = new CustomMultipartEntity(iProgressListener); // 文件传输
        try {
            mpEntity.addPart(MoccaApi.PARAM_UID, new StringBody(uid));
            mpEntity.addPart(MoccaApi.PARAM_FID, new StringBody(fid));
            mpEntity.addPart(MoccaApi.PARAM_TITLE, new StringBody(title, Charset.forName("GBK")));

            if (TextUtils.isEmpty(videoAidList)) {
                mpEntity.addPart(MoccaApi.PARAM_CONTENT,
                        new StringBody(content, Charset.forName("GBK")));
            } else {
                mpEntity.addPart(
                        MoccaApi.PARAM_CONTENT,
                        new StringBody(String.format("%s[petvideo]%s[/petvideo]", content,
                                videoAidList), Charset.forName("GBK")));
            }

            if (!TextUtils.isEmpty(webvideodata)) {
                mpEntity.addPart(MoccaApi.PARAM_WEBVIDEODATA,
                        new StringBody(webvideodata, Charset.forName("GBK")));
            }

            mpEntity.addPart(MoccaApi.PARAM_ISSHARE, new StringBody(String.valueOf(isSendShared)));

            if (!TextUtils.isEmpty(aidList)) {
                mpEntity.addPart(MoccaApi.PARAM_AIDLIST, new StringBody(aidList));
            }
            if (!TextUtils.isEmpty(videoAidList)) {
                mpEntity.addPart(MoccaApi.PARAM_VIDEOIDLIST, new StringBody(videoAidList));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String strReturn = "";
        try {
            String responseBody = post(MoccaApi.INDEXPOSTSURL, mpEntity);
            JSONObject result = new JSONObject(responseBody);
            if (result.getInt("result") == 0) {
                return new Pair<Boolean, String>(true, responseBody);
            } else {
                strReturn = result.getString("msg").toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            strReturn = "发送失败，已保存到草稿箱";
        }
        return new Pair<Boolean, String>(false, strReturn);
    }

    @Override
    public Pair<Boolean, String> post(String uid, String fid, String title, String content,
            String aidList, String videoAidList, String tid, String pid, String webvideodata,
            ProgressListener iProgressListener) {
        CustomMultipartEntity mpEntity = new CustomMultipartEntity(iProgressListener); // 文件传输
        try {

            mpEntity.addPart(MoccaApi.PARAM_UID, new StringBody(uid));
            mpEntity.addPart(MoccaApi.PARAM_FID, new StringBody(fid));
            mpEntity.addPart(MoccaApi.PARAM_TID, new StringBody(tid));
            if (!TextUtils.isEmpty(pid)) {
                mpEntity.addPart(MoccaApi.PARAM_REPQUOTE, new StringBody(pid));
            }
            if (!TextUtils.isEmpty(content)) {
                mpEntity.addPart(MoccaApi.PARAM_CONTENT,
                        new StringBody(content, Charset.forName("GBK")));// "UTF-8"
            }

            if (!TextUtils.isEmpty(webvideodata)) {
                mpEntity.addPart(MoccaApi.PARAM_WEBVIDEODATA,
                        new StringBody(webvideodata, Charset.forName("GBK")));
            }

            if (!TextUtils.isEmpty(aidList)) {
                mpEntity.addPart(MoccaApi.PARAM_AIDLIST, new StringBody(aidList));
            }
            if (!TextUtils.isEmpty(videoAidList)) {
                mpEntity.addPart(MoccaApi.PARAM_VIDEOIDLIST, new StringBody(videoAidList));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String strReturn = "";
        try {
            String responseBody = post(MoccaApi.POSTREPLY, mpEntity);
            JSONObject result = new JSONObject(responseBody);
            if (result.getInt("result") == 0) {
                return new Pair<Boolean, String>(true, responseBody);
            } else {
                strReturn = result.getString("msg").toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            strReturn = "发送失败，已保存到草稿箱";
        }
        return new Pair<Boolean, String>(false, strReturn);
    }

    protected final int BUFFER_SIZE = 4096;

    private byte[] getResponseData(HttpEntity entity) throws IOException {
        byte[] responseBody = null;
        if (entity != null) {
            InputStream instream = entity.getContent();
            if (instream != null) {
                long contentLength = entity.getContentLength();
                if (contentLength > Integer.MAX_VALUE) {
                    throw new IllegalArgumentException(
                            "HTTP entity too large to be buffered in memory");
                }
                int buffersize = (contentLength < 0) ? BUFFER_SIZE : (int) contentLength;
                try {
                    ByteArrayBuffer buffer = new ByteArrayBuffer(buffersize);
                    try {
                        byte[] tmp = new byte[BUFFER_SIZE];
                        int l, count = 0;
                        // do not send messages if request has been cancelled
                        while ((l = instream.read(tmp)) != -1
                                && !Thread.currentThread().isInterrupted()) {
                            count += l;
                            buffer.append(tmp, 0, l);
                            // sendProgressMessage(count, (int) contentLength);
                        }
                    } finally {
                        instream.close();
                    }
                    responseBody = buffer.toByteArray();
                } catch (OutOfMemoryError e) {
                    System.gc();
                    throw new IOException("File too large to fit into available memory");
                }
            }
        }
        return responseBody;
    }

}
